<?php
namespace App\Core;


class Response
{
    const CONFIG_N_COOKIE_DOMAIN = 'cookie_domain';
    const CONFIG_N_COOKIE_PATH = 'cookie_path';

    /**
     * @var App
     */
    protected $_app;

    public function __construct(App $app)
    {
        $this->_app = $app;
    }


    /**
     * 跳转指令
     * @param string $url 目的url
     * @param bool $permanent 是否为永久跳转301，默认为临时跳转302
     * @param bool $is_exit 是否提前终止框架运行
     */
    public function redirect($url, $permanent = false, $is_exit = true)
    {
        header("Location: $url", true, $permanent ? 301 : 302);
        //如果在controller中直接退出的话，会使得一些interceptor没有执行
        //为了不影响之前的代码，加了 is_exit参数
        if ($is_exit) {
            exit(0);
        }
    }

    public function setCookie($name, $value, $expire = 0, $path = NULL, $domain = NULL, $secure = FALSE, $httpOnly = FALSE)
    {
        if (!$path) {
            $path = $this->_app->getConfig(self::CONFIG_N_COOKIE_PATH);
        }
        if (!$domain) {
            $domain = $this->_app->getConfig(self::CONFIG_N_COOKIE_DOMAIN);
        }
        return setcookie($name, $value, $expire ? time() + intval($expire) : 0, $path, $domain, $secure, $httpOnly);
    }

    public function removeCookie($name, $path = NULL, $domain = NULL, $secure = FALSE, $httpOnly = FALSE)
    {
        return $this->setCookie($name, NULL, -3600, $path, $domain, $secure, $httpOnly);
    }


    public function setHeader($name, $value, $http_response_code = NULL)
    {
        header("$name: $value", TRUE, $http_response_code);
    }

    public function addHeader($name, $value, $http_response_code = NULL)
    {
        header("$name: $value", FALSE, $http_response_code);
    }

    /**
     * 设置返回内容的类型和字符集。默认字符集为utf-8，也可以在common.php里面指明。
     *
     * @param string $content_type 内容类型
     * @param string $charset 字符集
     */
    public function setContentType($content_type, $charset = NULL)
    {
        // 设置文本类型的字符集
        if (!$charset && preg_match('/^text/i', $content_type)) {
            $charset = $this->_app->getConfig('charset');
            if (!$charset) {
                $charset = 'utf-8';
            }
        }

        if ($charset) {
            $this->setHeader('Content-Type', "{$content_type}; charset={$charset}");
        } else {
            $this->setHeader('Content-Type', $content_type);
        }
    }

    public function setCacheControl($value)
    {
        $this->setHeader('cache-control', $value);
    }
}